<?php

namespace App\Models\Traits;

trait ModelSearchTrait
{
    //
    public function modelSearch($request,$model): object
    {
        if(count($this->searchConditions())){
            $model=$model->where(function ($query) use ($request) {
                foreach ($this->searchConditions() as $condition) {
                    $column=$condition[0];
                    $operator=$condition[1];
                    if($request->filled($column)){
                        switch ($operator){
                            case 'like':
                                $string = $this->transSpecialSearch($request->$column);
                                $query->where($column,$operator,'%'.$string.'%');
                                break;
                            case 'between':
                                $range=$request->$column;
                                $query->whereBetween($column,$range);
                                break;
                            default:
                                $query->where($column,$operator,$request->$column);
                                break;
                        }
                    }
                }
            });
        }
        return $model;
    }
    //
    public function transSpecialSearch($string):string
    {
        if(str_contains($string,'%')){
            $string = str_replace('%','\%',$string);
        }
        return $string;
    }

}
